package lvbu.wang.lvbuoperator.ui.index;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.qing.library.utils.StringUtil;
import com.qing.library.widget.CustomProgress;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yzq.zxinglibrary.common.Constant;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lvbu.wang.lvbuoperator.PrintQR1Ac;
import lvbu.wang.lvbuoperator.PrintQRAc;
import lvbu.wang.lvbuoperator.Quick;
import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.BleMotorInfo;
import lvbu.wang.lvbuoperator.bean.SendCommandResult;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.http.BleHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.ui.paramset.ui.BleParamSetActivity;
import lvbu.wang.lvbuoperator.ui.scan.BleBluetoothListActivity;
import lvbu.wang.lvbuoperator.utils.CommandUtils;
import lvbu.wang.lvbuoperator.utils.CommonUtil;
import lvbu.wang.lvbuoperator.utils.FormatUtil;
import lvbu.wang.lvbuoperator.utils.StringHelper;
import lvbu.wang.lvbuoperator.widget.CustDialog;

/**
 * Created by DaiQing.Zha on 2016/12/22 0022.
 * <p>
 * <p>
 * modidfy by 孟德
 * info: 原版本在扫码进入设置页面时,没有获取蓝牙的数据,
 * 增加获取数据并提交到服务器
 */

public class BleIndexActivity extends BaseActivity {

    private String TAG = "BleIndexActivity";
    private Button mBtnBleList; //蓝牙设备列表
    private Button btnBtnEWMScan; //蓝牙设备列表
    private CustomProgress mCustomProgress;  //自定义进度条

    private Dialog mDialog;
    private boolean isActivityShow = false;
    private boolean mIsOnShow = true;    //当前页面是否正在显示

    /**
     * 定义广播接收器，接收蓝牙消息
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            if (intent.getAction().equals(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED)) { //蓝牙状态改变
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(BleIndexActivity.this) == BluetoothLEService.Bluetooth_CONNECTED) {
                    Log.e(TAG, "连接OK,显示确定对话窗");
                    mCustomProgress.dissMiss();
                    if (!mDialog.isShowing() && isActivityShow) {
                        mDialog.show();
                    }
                }
                if (BaseActivity.getMotorDefault_bluetooth_connect_state(BleIndexActivity.this) == BluetoothLEService.Bluetooth_UNCONNECT) {
                    if (mIsOnShow) {
                        mCustomProgress.dissMiss();
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble_index);

        final View view = LayoutInflater.from(BleIndexActivity.this).inflate(R.layout.view_of_confirm_connected, null);
        CustDialog.Builder builder = new CustDialog.Builder(BleIndexActivity.this, view);
        builder.setOKDialogButton((dialog, which) -> {
            dialog.dismiss();
            Log.e(TAG, "获取信息并提交");
            initMotorInfo();
        });
        builder.setCancelDialogButton((dialog, which) -> {
            dialog.dismiss();
            Log.e(TAG, "取消提交");
            BluetoothLEService.disConnect();
        });
        mDialog = builder.create();
        mDialog.setCancelable(false);
        registerBroadcast();
    }

    /**
     * 初始化电机信息
     */
    private void initMotorInfo() {
        ThreadPool.getInstance().addTask(() -> {
            String[] commandHeads = {"BA", "BB", "AC", "A5", "A6", "AB"   //硬件版本,固件版本,蓝牙地址,助力等级,超速报警，轮胎周长
                    , "AE", "AF", "C3", "C4", "D2"   //车重,载重,电机状态,助力模式,上坡助力角度
                    , "D3", "D1", "D0"};    //上坡助力等级,电池功率,电池型号,电机系列
            StringBuffer sendCodeBuf = new StringBuffer();
            for (int i = 0; i < commandHeads.length; i++) {
                sendCodeBuf.append(commandHeads[i]);
            }
            String sendCode = sendCodeBuf.toString();
            sendCode = CommandUtils.FLAG_GET + sendCode;
            long start = System.currentTimeMillis();
            SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode, CommandUtils.getInquireCommand(commandHeads));
            Log.e(TAG, "藍牙連接時常：" + (System.currentTimeMillis() - start));
            Log.e(TAG, "sendCode1 " + sendCodeBuf + " sendCodeMM1 = " + CommandUtils.getInquireCommand(commandHeads) + " scr1 = " + scr.toString());
            if (scr.isResult()) {
                try {
                    String answerResult = StringHelper.subString(scr.getAnswerContent(), 6, 8);
                    if ("01".equals(answerResult)) {
                        BleMotorInfo bleMotorInfo = App.getInstance().getBleMotorInfo();
                        HashMap map = CommandUtils.getInquireMap(scr.getAnswerContent());
                        Set set1 = map.keySet();
                        for (Object obj : set1) {
                            if (obj.equals("BA")) {  //硬件版本
                                bleMotorInfo.setHardwareVersion(String.valueOf(map.get(obj)));
                                Log.e(TAG, "hardWareVersion = " + String.valueOf(map.get(obj)));
                            }
                            if (obj.equals("BB")) {  //固件版本
                                bleMotorInfo.setFirmwareVersion(String.valueOf(map.get(obj)));
                            }
                            if (obj.equals("AC")) {  //蓝牙地址
                                bleMotorInfo.setBluetoothAddress(CommonUtil.convertBluetoothAddress(String.valueOf(map.get(obj))));
                            }
                            if (obj.equals("A5")) {  //助力等级
                                bleMotorInfo.setPowerLevel(Integer.parseInt(String.valueOf(map.get(obj)), 16));   //助力等级
                                Log.e(TAG, "powerLevel = " + Integer.valueOf(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("A6")) {  //超速报警
                                bleMotorInfo.setSpeedLimitValue(Integer.parseInt(String.valueOf(map.get(obj)), 16));   //助力等级
                                Log.e(TAG, "speedLimit = " + Integer.valueOf(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("AB")) {  //轮胎周长
                                bleMotorInfo.setCircumference(FormatUtil.str2Float(String.valueOf(map.get(obj)), 3));
                            }
                            if (obj.equals("AE")) {  //车重
                                bleMotorInfo.setBikeWeight((float) Integer.parseInt(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("AF")) {  //载重
                                bleMotorInfo.setLoadWeight((float) Integer.parseInt(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("C3")) {  //电机状态
                                bleMotorInfo.setStatusCode(String.valueOf(map.get(obj)));
                            }
                            if (obj.equals("C4")) {  //助力模式
                                bleMotorInfo.setAssistantMode(String.valueOf(map.get(obj)));
                            }
                            if (obj.equals("D2")) {  //上坡助力角度
                                bleMotorInfo.setUpHillAngle(FormatUtil.str2Float(String.valueOf(map.get(obj)), 1));
                            }
                            if (obj.equals("D3")) {  //上坡助力等级
                                bleMotorInfo.setUpHillPowerLevel(Integer.parseInt(String.valueOf(map.get(obj)), 16));
                            }
                            if (obj.equals("D1")) {  //电池功率
                                Log.e(TAG, "D1 = " + map.get(obj));
                                bleMotorInfo.setBatteryRate(Integer.parseInt(String.valueOf(map.get(obj)), 16));   //电池功率数
                            }
                            if (obj.equals("D0")) {  //电机系列
                                bleMotorInfo.setMotorSeries(StringUtil.string2Ascii(String.valueOf(map.get(obj))));
                                Log.e(TAG, "D0 = " + StringUtil.string2Ascii(String.valueOf(map.get(obj))));
                            }
                        }
                        App.getInstance().setBikeMotor(bleMotorInfo);
                        Map<String, Object> queryStrings = new HashMap<>();
                        queryStrings.put("bluetoothAddress", bleMotorInfo.getBluetoothAddress());
                        queryStrings.put("hardwareVersion", bleMotorInfo.getHardwareVersion());
                        queryStrings.put("firmwareVersion", bleMotorInfo.getFirmwareVersion());
//                        long start = System.currentTimeMillis();
//                        showToastMsg("开始网络请求");
                        String source = BleHttpHelp.getData(RouteConstant.SET_MOTOR_INFO_VERSION_UPDATE, queryStrings, true, BleIndexActivity.this);
//                        showToastMsg("结束网络请求" + (System.currentTimeMillis() - start));
                        Log.e(TAG, "網絡請求：" + (System.currentTimeMillis() - start));
                        Log.e(TAG, "---source--- = " + source);
                        Log.e(TAG, "---bleMotorInfo--- = " + bleMotorInfo.toString());
                        if ("success".equals(source.replace("\"", ""))) {
//                            BluetoothLEService.disConnect();
                            if (mDialog.isShowing()) mDialog.dismiss();
                            startActivity(new Intent(BleIndexActivity.this, BleParamSetActivity.class));
                            Log.e(TAG, "跳转：" + (System.currentTimeMillis() - start));
                        } else {
                            BluetoothLEService.disConnect();
                            showToastMsg(source);
                        }
                    } else {
                        //TODO:返回不是01
                        runOnUiThread(() -> showToastMsg("获取数据失败！01"));
                        BluetoothLEService.disConnect();
                    }
                } catch (Exception e) {
                    Log.e(TAG, "error error = " + e.toString());
                    BluetoothLEService.disConnect();
                }
            } else {
                //TODO:应答失败
                runOnUiThread(() -> showToastMsg("获取数据失败！应答失败"));
                BluetoothLEService.disConnect();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsOnShow = true;
        isActivityShow = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mIsOnShow = false;
        isActivityShow = false;

    }

    @Override
    protected void init() {

        mBtnBleList = findView(R.id.btn_bleList);
        btnBtnEWMScan = findView(R.id.btn_EWMScan);
        mCustomProgress = new CustomProgress(this);
        mBtnBleList.setOnClickListener(v -> {
            // 蓝牙搜索6.0以上需要的权限
            AndPermission.with(BleIndexActivity.this).runtime().permission(Permission.ACCESS_COARSE_LOCATION)
                    .onGranted(data -> startActivity(new Intent(BleIndexActivity.this, BleBluetoothListActivity.class)))
                    .onDenied(data -> showToastMsg("权限获取失败，请手动开启权限")).start();
        });
        btnBtnEWMScan.setOnClickListener(v -> {
            Quick.startQRCode(BleIndexActivity.this, ConstantsValue.INTENT_SCAN_EWM1);
//                startActivityForResult(new Intent(BleIndexActivity.this, CaptureActivity.class), ConstantsValue.INTENT_SCAN_EWM1);
        });
        findViewById(R.id.btn_print).setOnClickListener(view -> startActivity(new Intent(this, PrintQRAc.class)));
        findViewById(R.id.btn_print1).setOnClickListener(view -> startActivity(new Intent(this, PrintQR1Ac.class)));
        getSupportActionBar().setTitle(getString(R.string.app_ble_name));
    }

    /**
     * 注册广播接收器
     */
    private void registerBroadcast() {
        IntentFilter filter;
        filter = new IntentFilter();
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED);
        this.registerReceiver(broadcastReceiver, filter);
    }

    /**
     * 解除广播注册
     */
    private void unRegisterBroadcast() {
        unregisterReceiver(broadcastReceiver);
    }

    /**
     * 开启相关权限
     */
    private void openAuthority() {
        new AlertDialog.Builder(this).setTitle(getString(R.string.comm_tip)).setMessage(getString(R.string.cameraLimit_dialogMsg)).setPositiveButton(getString(R.string.comm_sure), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.fromParts("package", getPackageName(), null));
                startActivity(intent);
            }
        }).setNegativeButton(getString(R.string.comm_cancel), null)
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isActivityShow = false;
        BluetoothLEService.disConnect();
        unRegisterBroadcast();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ConstantsValue.INTENT_SCAN_EWM1:   //从绑定车辆返回过来
                if (resultCode == RESULT_OK) {    //返回结果成功
                    Bundle bundle = data.getExtras();
                    String reStr = bundle.getString(Constant.CODED_CONTENT);
                    Log.e(TAG, reStr);
                    final String bleAddress = CommonUtil.convertBluetoothAddress(bundle.getString(Constant.CODED_CONTENT).trim().replace(" ", ""));
                    if (bleAddress.equals("error")) {
                        openAuthority();
                        return;
                    }
                    //蓝牙地址验证规则
                    String regEx = "^[A-Fa-f0-9:]+$";
                    // 编译正则表达式
                    Pattern pattern = Pattern.compile(regEx);
                    Matcher matcher = pattern.matcher(bleAddress);
                    // 字符串是否与正则表达式相匹配
                    boolean rs = matcher.matches();
                    if (!rs) {
                        showToastMsg("蓝牙地址无效！");
                        return;
                    }
                    Log.e(TAG, "---蓝牙地址--- = " + bleAddress);

                    BaseActivity.saveMotorDefault_bluetooth_connect_state(BleIndexActivity.this, BluetoothLEService.Bluetooth_UNCONNECT);    //设置蓝牙状态为已连接
                    BleMotorInfo bleMotorInfo = new BleMotorInfo();
                    bleMotorInfo.setBluetoothAddress(bleAddress);
                    App.getInstance().setBikeMotor(bleMotorInfo);
                    setBluetoothAddress(BleIndexActivity.this, bleAddress);
                    BluetoothLEService.connect();
                    Log.e(TAG, "正在连接蓝牙");
                    mCustomProgress.show(BleIndexActivity.this, "正在连接蓝牙", false, null, v -> {
                        CustomProgress.dissMiss();
                        BluetoothLEService.disConnect();
                    });

                }
        }
    }
}
